
package com.gitee.jmash.oidc.oauth2.controller;

import java.time.LocalDateTime;
import org.bouncycastle.util.encoders.Hex;
import com.gitee.jmash.crypto.cipher.CipherUtil;
import com.gitee.jmash.crypto.cipher.SM4CbcUtil;
import com.gitee.jmash.oidc.oauth2.OauthServerProps;
import com.gitee.jmash.oidc.oauth2.models.AuthzModel;
import com.gitee.jmash.oidc.web.Constant;
import com.gitee.jmash.oidc.web.models.RedirectResult;
import com.xyvcard.ops.OpsFactory;
import com.xyvcard.ops.entity.OpsClientEntity;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Inject;
import jakarta.mvc.Controller;
import jakarta.mvc.Models;
import jakarta.mvc.binding.BindingResult;
import jakarta.validation.Valid;
import jakarta.ws.rs.BeanParam;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;

/** OAuth2.0 authorize page. */
@Path("/private/authorize")
@Controller
@RequestScoped
public class AuthorizeController {

  @Inject
  private OauthServerProps oauthServerProps;

  @Inject
  private Models models;

  @Inject
  private BindingResult bindingResult;

  /** Base Redirect @RedirectScoped. */
  @Inject
  private RedirectResult redirectResult;

  /** 授权页面. */
  @GET
  public String authorize(@Valid @BeanParam AuthzModel authz) throws Exception {
    if (bindingResult.isFailed()) {
      redirectResult.addBindingResult(bindingResult);
      return "redirect:/login";
    }
    OpsClientEntity client =
        OpsFactory.getOpsClientRead(Constant.TENANT).findById(authz.getClientId());
    models.put("authz", authz);
    models.put("client", client);
    String value = client.getClientId() + "," + LocalDateTime.now();

    models.put("key", encrypt(value));
    return "oauth/authorize.ftl";
  }

  public String encrypt(String value) throws Exception {
    CipherUtil cipherUtil = SM4CbcUtil.get();
    byte[] key = cipherUtil.decodeKey(oauthServerProps.getSm4key());
    byte[] content = cipherUtil.encrypt(key, value.getBytes());
    return Hex.toHexString(content);
  }

}
